﻿using AutoMapper;
using ERPSystem.Common.Domains.PurchaseInvoiceCommon;
using ERPSystem.Common.Domains.WarehouseCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using SqlSugar;
using System.Transactions;

namespace SalesManagementWrite.API.SalesManagementWrites.PurchaseInvoicees
{
    public class PurchaseInvoiceCreateHandler : IRequestHandler<PurchaseInvoiceCreateCommand, Result>
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly IBaseRepository<PurchaseInvoice> _purchaseInvoiceRepository;
        private readonly IBaseRepository<PurchaseInvoiceSubtable> _purchaseInvoiceSubtableRepository;
        private readonly IMapper _mapper;

        public PurchaseInvoiceCreateHandler(ISqlSugarClient sqlSugarClient, IBaseRepository<PurchaseInvoice> purchaseInvoiceRepository, IBaseRepository<PurchaseInvoiceSubtable> purchaseInvoiceSubtableRepository, IMapper mapper)
        {
            _sqlSugarClient = sqlSugarClient;
            _purchaseInvoiceRepository = purchaseInvoiceRepository;
            _purchaseInvoiceSubtableRepository = purchaseInvoiceSubtableRepository;
            _mapper = mapper;
        }


        /// <summary>
        /// 新增采购发票
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PurchaseInvoiceCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            _sqlSugarClient.Ado.BeginTran();
            try
            {
                var purchaseInvoice = new PurchaseInvoice()
                {
                    PurchaseInvoiceId = request.PurchaseInvoiceId,
                    SerialNumber = request.SerialNumber,//流水号雪花ID
                    DocumentNo = request.DocumentNo,
                    BusinessType = request.BusinessType,
                    Vendor = request.Vendor,
                    BillingDate = request.BillingDate,
                    OnInvoice = request.OnInvoice,
                    DocumentDate = request.DocumentDate,
                    Operator = request.Operator,
                    TaxNo = request.TaxNo,
                    RedBasketLetter = request.RedBasketLetter,
                    XMLFormat = request.XMLFormat,
                    DocumentStatus = request.DocumentStatus,
                    Auditors = request.Auditors,
                    InvoiceTypeId = request.InvoiceTypeId,
                    InvoiceAmount = request.InvoiceAmount,
                    OFPFormat = request.OFPFormat,
                    BusinessStatusId = request.BusinessStatusId,
                    DateOfReview =DateTime.Now,
                    InvoiceCode = request.InvoiceCode,
                    Tax = request.Tax,
                    InvoiceStatus = request.InvoiceStatus,
                    InvoiceNumber = request.InvoiceNumber,
                    PriceTaxTotal = request.PriceTaxTotal,
                    RemarkInfo = request.RemarkInfo,
                };
                var purchaseInvoices = await _purchaseInvoiceRepository.Add(purchaseInvoice);
                List<PurchaseInvoiceSubtable> purchaseInvoiceSubtables = new List<PurchaseInvoiceSubtable>();
                foreach (var item in request.purchaseInvoiceSubtables)
                {
                    purchaseInvoiceSubtables.Add(new PurchaseInvoiceSubtable()
                    {
                        PurchaseInvoiceSubtableId = item.PurchaseInvoiceSubtableId,
                        PurchaseON = item.PurchaseON,
                        Warehouse = item.Warehouse,
                        InventoryRN = item.InventoryRN,
                        LogisticsCode = item.LogisticsCode,
                        NameOfLogistics = item.NameOfLogistics,
                        ModelSpecification = item.ModelSpecification,
                        MainMetering = item.MainMetering,
                        Num = item.Num,
                        Price = item.Price,
                        Amount = item.Amount,
                        TaxRate = item.TaxRate,
                        AmountOfTax = item.AmountOfTax,
                        SerialNumber = purchaseInvoice.SerialNumber,//流水号外键
                    });
                }
                var purchaseInvoiceSubtableResult = await _purchaseInvoiceSubtableRepository.AddRange(purchaseInvoiceSubtables);
                if (purchaseInvoices > 0 && purchaseInvoiceSubtableResult > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                _sqlSugarClient.Ado.CommitTran();
                return result;
            }
            catch (Exception ex)
            {
                _sqlSugarClient.Ado.RollbackTran();
                throw ex;
            }
        }

    }
}
